﻿// <copyright file="KeyAttributeDictionary.cs" company="Codeplex project Eco.Contrib"> 
// The MIT License (MIT) 
// </copyright> 
// <author>Peter Buchmann</author> 

namespace Eco.Contrib
{
    using System;
    using System.Collections.Generic;
using System.Runtime.Serialization;

    /// <summary>
    /// KeyAttributeDictionary: Key attribute dictionary
    /// </summary>
    [Serializable]
    public class KeyAttributeDictionary : Dictionary<Type, string>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="KeyAttributeDictionary"/> class.
        /// </summary>
        /// <param name="info">The info.</param>
        /// <param name="context">The context.</param>
        protected KeyAttributeDictionary(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// Gets the key attribute for the type.
        /// </summary>
        /// <param name="type">The t.</param>
        /// <returns>Key attribute for the type</returns>
        public string KeyAttributeForType(Type type)
        {
            Type tempType = type;
            while (!this.ContainsKey(tempType) && tempType != null)
            {
                tempType = tempType.BaseType;
            }

            if (tempType != null)
            {
                string keyAttribute = this[tempType];
                if (type != tempType)
                {
                    this[type] = keyAttribute;
                }

                return keyAttribute;
            }

            throw new EcoContribException("No key attribute defined for class " + tempType.Name);
        }
    }
}
